<?php

namespace App\Http\Controllers\UserApi;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Services\Api\EasyWeChatService;

class LoginController extends BaseController
{
    //账号登录接口
    public function login(Request $request,User $user){
        $account_user = $user->where('phone',$request->input('phone'))->first();
        $token = JWTAuth::fromUser($account_user);
        $account_user->token = $token;
        return $account_user;
    }

    //微信登录接口
    public function wx_login(Request $request,User $user){

        $input = $request->post();
        $EasyApp = EasyWeChatService::easy_app();
        $session = $EasyApp->auth->session($input['wx_code']);

        // 说明没有获取到openid
        if(empty($session['openid'])){
            throw new \Exception($session['errmsg']);
        }

        // 查找會員是否存在
        $userObj = $user
            -> where('wx_openid','=',$session['openid'])
            -> first();

        if(empty($userObj)){
            $decryptedData = $EasyApp->encryptor->decryptData($session['session_key'],$input['wx_iv'],$input['encryptedData']);
            if(!key_exists('wx_iv',$input) && !key_exists('encryptedData',$input)){
                throw new \Exception('wx_iv和encryptedData必传');
            }
            if(empty($decryptedData['avatarUrl'])){
                throw new \Exception('解密失败 请检查参数');
            }

            $user->refresh;
            //头像
            $avatar = getWxHead($decryptedData['avatarUrl']);

            $user['head_img'] = $avatar;
            $data['nickname'] = $decryptedData['nickName'];
            $data['wx_openid'] = $decryptedData['openId'];

            $user->insert($data);
            $userObj =  $user;
        }

        // 自動登錄
        $token = JWTAuth::fromUser($userObj);
        $userObj->token = $token;

        return $this->success($userObj);

    }
}
